package xyz.lilei23.framework.bean;

import xyz.lilei23.framework.annotation.AutoWired;
import xyz.lilei23.framework.core.BeanFactory;
import xyz.lilei23.framework.utils.ClassHelper;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author jack
 * @date 31/07/2021 16:20
 * @version 1.0
 **/
public class AutowiredInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * bean工厂
     */
    private BeanFactory beanFactory;


    public AutowiredInstantiationAwareBeanPostProcessor(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws RuntimeException {
        Field[] declaredFields;
        if (ClassHelper.isCglibProxyClassName(bean.getClass().getName())){
            declaredFields = bean.getClass().getSuperclass().getDeclaredFields();
        }else {
            declaredFields = bean.getClass().getDeclaredFields();
        }
        for (Field declaredField : declaredFields) {
            AutoWired autoWired = declaredField.getAnnotation(AutoWired.class);
            if (autoWired != null){
                if(Modifier.isStatic(declaredField.getModifiers())){
                    throw new RuntimeException("AutoWired不支持静态方法");
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(bean, beanFactory.getBean(declaredField.getType()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException("autoWired 动态设值异常");
                }
            }
        }
        return bean;
    }

}
